package com.codeyang.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codeyang.constant.RoleConstant;
import com.codeyang.domain.SysRole;
import com.codeyang.mapper.SysRoleMapper;
import com.codeyang.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.List;

/**
 * 描述: TO-删除标志-DO
 *
 * @author CodeYang_Site
 * @version 2021/5/24 10:03
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {


    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 全查询角色
     * see: 80%的数据都要存到缓存中
     * 三步走
     *
     * @return
     */
    @Override
    public List<SysRole> list() {
        //1.查 cache
        List<SysRole> list = null;
        //只有登录的才可以查看角色列表,这里应该是全查询 ?TODO 这里为什么不从角色中拿id+角色前缀来拿
        String roleListStr = redisTemplate.opsForValue().get(RoleConstant.ROLE_PREFIX);
        if (StringUtils.hasText(roleListStr)) {
            list = JSON.parseArray(roleListStr, SysRole.class);
            return list;
        }
        //2.没有就查询DB
        list = sysRoleMapper.selectList(null);
        //3.存DB
        if (!CollectionUtils.isEmpty(list)) {
            redisTemplate.opsForValue().set(RoleConstant.ROLE_PREFIX, JSON.toJSONString(list), Duration.ofDays(7));
        }
        return list;
    }
}
